package cn.xk.org.service.impl;

import cn.xk.basic.service.impl.BaseServiceImpl;
import cn.xk.org.domain.Department;
import cn.xk.org.mapper.DepartmentMapper;
import cn.xk.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：部门
 */
@Service //表明当前类在Service层，用这个注解，需要扫描包路径
//事务管理注解，查询用这个，propagation = Propagation.SUPPORTS代表只读不操作。
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService  {
    @Autowired //自动注入注解，对当前对象实例化
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        //1.将所有部门信息保存在map中，方便根据id去获取部门信息，就不用查数据库了
        Map<Long, Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(), department);
        }

        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if (department.getParent_id() == null) {//顶级部门
                //2.遍历所有的部门，如果是顶级部门[parent_id==null],加到部门树
                deptTree.add(department);
            } else {
                //3.如果不是顶级部门[parent_id!=null],找到自己的父部门，将自己加到父部门的children
                //获取父部门的id - 获取父部门对象 - 获取父部门的children集合
                Long parentId = department.getParent_id();
                //根据id获取父部门
                Department parentDepartment = map.get(parentId);
                //防止父部门的数据删除引起的空指针异常
                if (parentDepartment != null) {
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }

}
